package com.ch.base.factory;

import java.sql.Connection;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionSupport;

public abstract class ActionFactory extends ActionSupport {
	private final Logger log = Logger.getLogger(this.getClass());
	
	/**
	 * <P>繼承此抽象類別需要實作此函式</P>
	 */
	public abstract String execute() throws Exception;

	/**
	 * <P>取得資料庫 Connection 物件</P>
	 * @return Connection 資料庫的連線
	 * @throws Exception 取得連線發生問題拋出
	 */
	protected synchronized Connection getConnection() throws Exception {
		Connection conn = null;
		try {
			conn =  new ConnectionFactory().getConnection();
		} catch (Exception e) {
			log.error("BaseAction.getConnection(): Get Connection failed");
			conn.rollback();
			conn.close();
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	
	/**
	 * <P>取得指定資料庫的 Connection 物件</P>
	 * @param dbName 資料庫名稱，此名稱為登記在 database.properties 內的參數名稱
	 * @return Connection 資料庫的連線
	 * @throws Exception 取得連線發生問題拋出
	 */
	protected synchronized Connection getConnection(String dbName) throws Exception {
		Connection conn = null;
		try {
			conn =  new ConnectionFactory(dbName).getConnection();
		} catch (Exception e) {
			log.error("BaseAction.getConnection(dbName): Get Connection failed");
			conn.rollback();
			conn.close();
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	
	protected synchronized Connection getDBPoolConnection() throws Exception {
		Connection conn = null;
		try {
			conn =  new ConnectionFactory().getDBPoolConnection();
		} catch (Exception e) {
			log.error("BaseAction.getDBPoolConnection(): Get Connection failed");
			conn.rollback();
			conn.close();
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	
	protected synchronized Connection getDBPoolConnection(String dbName) throws Exception {
		Connection conn = null;
		try {
			conn =  new ConnectionFactory(dbName).getDBPoolConnection();
		} catch (Exception e) {
			log.error("BaseAction.getDBPoolConnection(dbName): Get Connection failed");
			conn.rollback();
			conn.close();
			e.printStackTrace();
			throw e;
		}
		return conn;
	}
	
}
